﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kooboo.Commerce;

using Kooboo.IoC;

namespace Kooboo.Web.Areas.Commerce.Binders
{
    public class TaxBinder:EntityBinder
    {
        protected override string[] SkipProperties
        {
            get
            {
                return new string[] { "SubTaxes"  };
            }
        }

        protected override object CreateModel(ControllerContext controllerContext,
            ModelBindingContext bindingContext, Type modelType)
        {
            var model = ObjectContainer.CreateInstance<ITax>();

            var form = controllerContext.HttpContext.Request.Form;

            model.SubTaxes = new List<ISubTax>();

            var indexes = form["SubTaxes.index"];

            if (string.IsNullOrWhiteSpace(indexes) == false)
            {
                foreach(var i in indexes.Split(','))
                {
                    var prefix = "SubTaxes[" + i + "]";

                    var subtax = ObjectContainer.CreateInstance<ISubTax>();
                    int id;
                    if (int.TryParse(form[prefix + ".Id"],out id))
                    {
                        subtax.Id = id;
                    }
                    else
                    {
                        subtax.Id = -1;
                    }

                    var country = ObjectContainer.CreateInstance<ICountry>();
                    country.CountryCode = form[prefix + ".Country.Code"];

                    subtax.Country = country;

                    subtax.State = form[prefix + ".State"];
                    decimal percent;
                    if (decimal.TryParse(form[prefix + ".Percent"], out percent))
                    {
                        subtax.Percent = percent;
                    }
                    else
                    {
                        subtax.Percent = decimal.Zero;
                    }

                    model.SubTaxes.Add(subtax);

                }
            }
            
            return model;

            
        }
    }
}